package com.oocl.multiple_threads_download;

import java.io.File;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.oocl.multiple_threads_download.analyzer.DownloadAnalyzer;
import com.oocl.multiple_threads_download.pojo.DownloadParams;
import com.oocl.multiple_threads_download.runnable.DownloadRunnable;

public class Downloader {

	private DownloadAnalyzer mAnalyer = new DownloadAnalyzer();
	
	/**
	 * 下载目标文件，并保存在指定目录
	 * @param filePath
	 * @param downloadPath
	 */
	public void downloadFile(String filePath, String downloadPath) {
		///分析文件大小，得到各种参数
		DownloadParams params =  this.mAnalyer.anaylzeFile(filePath);
		
		if(params== null) {
			System.out.println("要下载的文件地址可能输入有误");
		}
		
		params.setDownloadPath(downloadPath);
		
		///准备下载
		System.out.println("开始下载文件。。。。。请稍等。。。");
		long size  = params.getFileByteSize()/10;
		long rest = params.getFileByteSize()%10;
		Thread thread1 = new Thread(new DownloadRunnable(params, 0, size));
		Thread thread2 = new Thread(new DownloadRunnable(params, size+1, 2*size));
		Thread thread3 = new Thread(new DownloadRunnable(params, 2*size+1, 3*size));
		Thread thread4 = new Thread(new DownloadRunnable(params, 3*size+1, 4*size));
		Thread thread5 = new Thread(new DownloadRunnable(params, 4*size+1, 5*size));
		Thread thread6 = new Thread(new DownloadRunnable(params, 5*size+1, 6*size));
		Thread thread7 = new Thread(new DownloadRunnable(params, 6*size+1, 7*size));
		Thread thread8 = new Thread(new DownloadRunnable(params, 7*size+1, 8*size));
		Thread thread9 = new Thread(new DownloadRunnable(params, 8*size+1, 9*size));
		Thread thread10 = new Thread(new DownloadRunnable(params,9*size+1, params.getFileByteSize()-1));
		
		thread1.start();
		thread2.start();
		thread3.start();
		thread4.start();
		thread5.start();
		thread6.start();
		thread7.start();
		thread8.start();
		thread9.start();
		thread10.start();
		
		
		System.out.println("多线程下载文件成功，下载目录为："+ (new File(downloadPath)).getAbsolutePath());
	}
	
	
	public static void main(String[] args) {
		Downloader downloader = new Downloader();
//		downloader.downloadFile("/Users/androidjp/test.jpg", "download/test.jpg");
		Scanner scanner = new Scanner(System.in);
		String cmd;
		System.out.println("请输入如： <要下载文件地址> <下载到地址> 的命令：");
		while((cmd = scanner.nextLine())!=null) {
			if(cmd.equals("exit"))
				break;
			String[] ss  = cmd.split("\\s");
			if(ss== null || ss.length<2)
				continue;
			downloader.downloadFile( ss[0], ss[1]);
			System.out.println("请输入如： <要下载文件地址> <下载到地址> 的命令：");
		}
	}
	
	
}
